package com.txm.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.txm.activityMQ.Producer;
import com.txm.model.Blog.Article;
import com.txm.service.SysService;
import common.model.Result;
import common.util.UploadUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.collections.map.LinkedMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.SortParameters;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.query.SortQueryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.jms.JMSException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by tangxinmao on 2016/11/22.
 */
@Controller
@RequestMapping("sys")
public class SysController extends BaseController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SysService sysService;
 /*   @Autowired*/
    private Producer producer;

    /**
     * 登陆
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param result
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Model model, Result result) throws IOException {
        Object k = httpServletRequest.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        Object kaptchaSessionKey = httpServletRequest.getParameter("kaptchaSessionKey");
        Object userName = httpServletRequest.getParameter("userName");
        Object password = httpServletRequest.getParameter("password");
        if (k == null || !k.equals(kaptchaSessionKey)) {
            result.setMessage("验证码错误!");
        } else if (!(userName.equals("administrator") && password.equals("administrator"))) {
            result.setMessage("用户名或密码错误!");
        } else {
            redisTemplate.boundSetOps("sessionIds").add(httpServletRequest.getSession().getId());
            return "redirect:index";
        }
        result.setResult(false);
        httpServletResponse.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = httpServletResponse.getWriter();
        String json = JSON.toJSONString(result);
        printWriter.write(json);
        IOUtils.closeQuietly(printWriter);
        return null;
    }

    /**
     * 后台首页
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     */
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Model model) throws SigarException, IOException, JMSException {
        //new UploadUtil().upload();
        //cpu mem
        // producer.sendMessage(new User());
        Sigar sigar = new Sigar();
        CpuPerc cpu = sigar.getCpuPerc();
        model.addAttribute("combined", (int) (cpu.getCombined() * 100) + "%");
        Mem mem = sigar.getMem();
        model.addAttribute("usedPercent", (int) (mem.getUsedPercent()) + "%");
        //访问platform统计
        Map<Object, Object> operatingSystem = redisTemplate.opsForHash().entries("operatingSystem");
        Map<Object, Object> browser = redisTemplate.opsForHash().entries("browser");
        model.addAttribute("operatingSystem", operatingSystem);
        model.addAttribute("browser", browser);
        model.addAttribute("operatingSystemTotal", redisTemplate.opsForValue().get("operatingSystemTotal"));
        model.addAttribute("browserTotal", redisTemplate.opsForValue().get("browserTotal"));
        //周访问量统计
        List weekPV = redisTemplate.opsForList().range("weekPV", 0, 7);
        model.addAttribute("weekPV", weekPV);
        return "index";
    }

    @RequestMapping(value = "sigar")
    public void sigar(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws SigarException, IOException, InterruptedException {
        Sigar sigar = new Sigar();
        CpuPerc cpu = sigar.getCpuPerc();
        Map m = new HashedMap();
        m.put("combined", (int) (cpu.getCombined() * 100) + "%");
        Mem mem = sigar.getMem();
        m.put("usedPercent", (int) (mem.getUsedPercent()) + "%");
        String json = JSON.toJSONString(m);
        httpServletResponse.setContentType("text/event-stream");
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write("data:" + json + "\n\n");
        IOUtils.closeQuietly(writer);

    }

    /**
     * 退出登录
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws IOException
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        httpServletRequest.getSession().invalidate();//销毁session
        httpServletResponse.sendRedirect("/sign-in.jsp");
    }

    @RequestMapping(value = "article-add", method = RequestMethod.GET)
    public String articleAddIndex() {
        return "article-add";
    }

    @RequestMapping(value = "articleAdd", method = RequestMethod.POST)
    public String articleAdd(@RequestParam("multipartFile") MultipartFile multipartFile, HttpServletRequest request, Article
            article, HttpServletResponse response) throws IOException {
        String path = request.getSession().getServletContext().getRealPath("/");
        File file = new File(path, UUID.randomUUID().toString());
        //上传到工程
        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
        IOUtils.closeQuietly(multipartFile.getInputStream());
        //上传到云服务器
        UploadUtil.upload(file);
        //保存文章
        article.setImage(file.getName());
        sysService.articleAdd(article);
        return null;
    }

    @RequestMapping(value = "article-list", method = RequestMethod.GET)
    public String articleListIndex(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Model model, Article article, Page<Article> articlePage) {
        articlePage = sysService.articleList(article, articlePage);
        model.addAttribute("articlePage", articlePage);
        return "article-list";
    }

    @RequestMapping(value = "calendar", method = RequestMethod.GET)
    public String calendarIndex() {
        return "calendar";
    }

    /**
     * 添加日历
     *
     * @param start
     * @param end
     * @param title
     * @return
     */
    @RequestMapping(value = "calendarAdd", method = RequestMethod.POST)
    @ResponseBody
    public Result calendar(Date start, Date end, String title) {
        Result result = new Result();
        Map calendar = new LinkedMap();
        calendar.put("start", start);
        calendar.put("end", end);
        calendar.put("title", title);
        String json = JSON.toJSONString(calendar);
        redisTemplate.boundListOps("calendar").rightPush(json);
        return result;
    }

    /**
     * 获取日历
     *
     * @return
     */
    @RequestMapping(value = "calendarList", method = RequestMethod.POST)
    @ResponseBody
    public List calendarList() {
        List<String> list = redisTemplate.boundListOps("calendar").range(0, redisTemplate.boundListOps("calendar").size());
        return list;
    }

    /**
     * 提醒时钟
     *
     * @return
     */
    @RequestMapping(value = "calendarClock", method = RequestMethod.POST)
    @ResponseBody
    public List calendarClock() {
        SortQueryBuilder<String> builder = SortQueryBuilder.sort("calendar");
        builder.alphabetical(true);//对字符串使用字典顺序
        builder.order(SortParameters.Order.ASC);//倒序
        builder.limit(0, 3);
        List<String> list = redisTemplate.sort(builder.build());
        return list;
    }


}
